<template>
  <div>
    <!-- 卡片视图区域 -->
    <el-card class="card">
      <!-- 提示区域 -->
      <el-alert :title="alertTitle" type="info" center show-icon :closable="false"></el-alert>
      <!-- 步骤条区域 -->
      <el-steps :active="activeIndex - 0" finish-status="success" align-center class="steps">
        <el-step title="基本信息" icon="el-icon-edit"></el-step>
        <el-step title="上传封面和视频" icon="el-icon-upload"></el-step>
        <el-step title="完成" icon="el-icon-circle-check"></el-step>
      </el-steps>

      <!-- tab栏区域 -->
      <el-form
        :model="courseForm"
        :rules="courseFormRules"
        ref="courseFormRef"
        label-width="100px"
        label-position="top"
      >
        <el-tabs v-model="activeIndex" :tab-position="'left'" :before-leave="beforeTabLeave">
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="课程名称" prop="name">
              <el-input v-model="courseForm.name"></el-input>
            </el-form-item>
            <el-form-item label="教师名称" prop="teacher">
              <el-input v-model="courseForm.teacher"></el-input>
            </el-form-item>
            <el-form-item label="课程类别" prop="type">
              <el-select v-model="courseForm.type">
                <el-option
                  v-for="item in type_options"
                  :key="item.id"
                  :label="item.type"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="所属机构" prop="org_id">
              <el-select
                v-model="courseForm.org_id"
                filterable
                remote
                placeholder="请输入机构名称进行搜索"
                :remote-method="remoteMethod"
              >
                <el-option
                  v-for="item in org_options"
                  :key="item.id"
                  :label="item.schoolName"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="课程介绍" prop="introduction">
              <el-input type="textarea" v-model="courseForm.introduction"></el-input>
            </el-form-item>
            <el-button @click="nextOne">下一步</el-button>
          </el-tab-pane>
          <!-- 1区 -->
          <el-tab-pane label="上传封面和视频" name="1">
            <!-- 渲染表单的Item项 -->
            <el-form-item label="上传封面（可选）">
              <!-- 复选数组 -->
              <el-upload
                class="avatar-uploader"
                action="http://114.55.218.93:8081/minio/upload"
                :on-success="handleAvatarSuccess"
                list-type="picture-card"
                :file-list="fileList"
                :limit="1"
              >
                <i class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
            <el-form-item label="上传视频（可选）">
              <el-upload
                class="upload-demo"
                drag
                action="http://114.55.218.93:8081/minio/upload"
                :on-success="handleVideoSuccess"
                :on-remove="handleVideoRemove"
                :file-list="videoList"
                multiple
              >
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">
                  将文件拖到此处，或
                  <em>点击上传</em>
                </div>
              </el-upload>
            </el-form-item>
            <el-button type="primary" @click="submit">{{ btnText }}</el-button>
            <!-- 2区 -->
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
  </div>
</template>

<script lang="ts">
import _ from 'lodash'
import { addCourse, getCourseById, editCourse, addVideo, getVideo, deleteVideo, getUniv, getUnivByName, getUnivById } from '#/CourseManagement/course'
import { getAllType } from '@/api/CourseManagement/courseType'
import { addLogs } from '@/api/Home/Home'
export default {
  data() {
    return {
      editId: '',
      alertTitle: '添加课程信息',
      btnText: '创建课程',
      courseForm: {
        name: "",
        org_id: '',
        teacher: "",
        type: "",
        // introduction: "",
        // cover: ""
      },
      // 发布新公告表单规则
      courseFormRules: {
        name: [
          { required: true, message: "请输入课程名", trigger: "blur" },
        ],
        teacher: [
          { required: true, message: "请输入教师名称", trigger: "blur" },
        ],
        type: [
          { required: true, message: "请输入类型", trigger: "blur" },
        ],
        org_id: [
          { required: true, message: "请选择机构", trigger: "blur" },
        ]
      },
      type_options: [],
      org_options: [],
      activeIndex: '0',
      fileList: [],
      videoList: [],
      newVideos: [],
      deleteList: []
    }
  },
  created() {
    if (this.$route.query.id) {
      this.editId = this.$route.query.id
      this.alertTitle = '修改课程信息'
      this.btnText = '修改课程'
      this.getCourseById();
      this.getVideoById();
    }
    this.getType();
    this.getUniOrg();
  },
  methods: {
    async getCourseById() {
      await getCourseById(this.editId).then(async res => {
        if (res.data.ret === 0) {
          this.courseForm = res.data.courses.courses
          this.fileList = [{ name: '1.jpg', url: this.courseForm.cover }]
          console.log(this.courseForm)
          await getUnivById(this.courseForm.id).then(res => {
            if (res.status === 200) {
              // e.org_id = res.data.yniv.schoolName
              this.$set(this.courseForm, 'org_id', res.data.yniv.schoolName)
            }
          })
        }
      })
    },
    async getVideoById() {
      await getVideo(this.editId).then(res => {
        if (res.status === 200) {
          res.data.course_videos.videos.forEach(e => {
            this.videoList.push({
              id: e.id,
              name: e.name,
              url: e.video
            })
          })
        }
      })
    },
    async getType() {
      await getAllType().then(res => {
        if (res.status === 200) {
          this.type_options = res.data.courseTypes.types
        }
      })
    },
    async getUniOrg() {
      await getUniv().then(res => {
        if (res.status === 200) {
          this.org_options = res.data.orgs.univ.content
        } else {
          return this.$message.error('获取机构数据错误')
        }
      })
    },
    async remoteMethod(query) {
      if (query) {
        await getUnivByName(query).then(res => {
          if (res.status === 200) {
            this.org_options = res.data.orgs.univ
          }
        })
      } else {
        this.org_options = []
      }

    },
    beforeTabLeave(activeName, oldActiveName) {
      // console.log('即将离开：' + oldActiveName)
      // console.log('即将进入：' + activeName)
      if (oldActiveName === '0' && (!this.courseForm.name || !this.courseForm.type || !this.courseForm.teacher || !this.courseForm.org_id)) {
        this.$message.error('请先填写课程基本信息！')
        return false
      }
    },
    handleAvatarSuccess(res) {
      if (res.ret === 0) {
        this.courseForm.cover = res.url
        this.$message.success('上传成功！')
      }
    },
    handleVideoSuccess(res, file, fileList) {
      if (res.ret === 0) {
        this.newVideos.push({
          name: file.name,
          url: file.response.url,
          uid: file.uid
        })
      }
      console.log(this.newVideos)
    },
    handleVideoRemove(res, fileList) {
      console.log(res)
      if (res.id) {
        // 删除原有的视频
        this.deleteList.push(res.id)
      }
      // 删除新添加但还没保存的视频
      let i = 0;
      let flag = false;
      for (i = 0; i < this.newVideos.length; i++) {
        if (this.newVideos[i].uid === res.uid) {
          flag = true;
          break;
        }
      }
      if (flag) {
        this.newVideos.splice(i, 1)
      }
    },
    nextOne() {
      this.activeIndex = '1'
    },
    async submit() {
      if (this.editId) {
        delete this.courseForm.typeInfo
        await editCourse(this.editId, this.courseForm).then(async res => {
          if (res.data.ret === 0) {
            this.$message.success('修改课程成功！')
            await addLogs({
              userId: window.sessionStorage.getItem('userId'),
              behavior: '修改了《' + this.courseForm.name + '》课程',
            })
            // 删除旧的课程
            if (this.deleteList.length > 0) {
              this.deleteList.forEach(async e => {
                await deleteVideo(e).then(res => {
                  console.log(res)
                })
              })
            }
            // 添加新的课程
            this.newVideos.forEach(async e => {
              await addVideo({
                courseId: this.editId,
                name: e.name,
                video: e.url
              }).then(response => {
                console.log(response)
              })
            })
            this.$router.push('/CourseManagement/course')
          } else {
            this.$message.error('修改失败，请检查重试！')
          }
        })
      } else {
        await addCourse(this.courseForm).then(async res => {
          if (res.data.ret === 0) {
            this.$message.success('创建课程成功！')
            await addLogs({
              userId: window.sessionStorage.getItem('userId'),
              behavior: '添加了《' + this.courseForm.name + '》课程',
            })
            // 添加视频课程
            let courseId = res.data.msg.split(' ')[1]
            this.newVideos.forEach(async e => {
              await addVideo({
                courseId,
                name: e.name,
                video: e.url
              }).then(response => {
                console.log(response)
              })
            })
            // 添加结束，跳转回去课程页面
            this.$router.push('/CourseManagement/course')
          } else {
            this.$message.error('创建失败，请检查重试！')
          }
        })
      }

    }
  },
}
</script>

<style lang="scss" scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100%;
  height: 100%;
  line-height: 100%;
  text-align: center;
}
.avatar {
  width: 100%;
  height: 100%;
  display: block;
}
.steps {
  margin: 20px 0;
}
</style>
